package g

import (
	"sync"

	"github.com/BurntSushi/toml"
)

var (
	c     *Config
	cOnce sync.Once
)

type Config struct {
	HttpConfig      HttpConfig      `toml:"http"`
	MysqlConfig     MysqlConfig     `toml:"mysql"`
	FheSearchConfig FheSearchConfig `toml:"fhe_search"`
	// CommonConfig    CommonConfig    `toml:"common"`
}

type HttpConfig struct {
	Host string `toml:"host"`
	Port int    `toml:"port"`
}

type MysqlConfig struct {
	Host     string `toml:"host"`
	Port     int    `toml:"port"`
	User     string `toml:"user"`
	Password string `toml:"password"`
	DbName   string `toml:"dbname"`
}

type FheSearchConfig struct {
	EncryptType   string `toml:"encrypt_type"`
	SecretKeyPath string `toml:"secret_key_path"`
	FileBasePath  string `toml:"file_base_path"`
}

// type CommonConfig struct {
// 	OsType string `toml:"os_type"`
// }

func ReadConfig(filePath string) {
	cOnce.Do(func() {
		config := Config{}
		_, err := toml.DecodeFile(filePath, &config)
		if err != nil {
			panic(err)
		}
		// config检查:
		// 1 path必须以正斜线结尾
		fileBasePath := config.FheSearchConfig.FileBasePath
		secretKeyPath := config.FheSearchConfig.SecretKeyPath
		if fileBasePath[len(fileBasePath)-1] != '/' || secretKeyPath[len(secretKeyPath)-1] != '/' {
			panic("file_base_path and secret_key_path must end with '/'")
		}
		// 2 encrypt_type 仅支持两个值 soft_encrypt or card_encrypt
		encryptType := config.FheSearchConfig.EncryptType
		if !(encryptType == "soft_encrypt" || encryptType == "card_encrypt") {
			panic("encrypt_type must be 'soft_encrypt' or 'card_encrypt', but you give " + encryptType)
		}
		c = &config
	})
}

func GetConfig() *Config {
	if c == nil {
		const DefaultConfigFilePath = "cfg.toml"
		ReadConfig(DefaultConfigFilePath)
	}
	return c
}
